package cn.com.hp.feature.service.impl;

import cn.com.hp.feature.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author hongjuzhu
 * @date 2022/3/28
 */
@Service
@Slf4j
public class FileService implements IFileService {

    @Override
    public void download(HttpServletResponse response, String filePath, String fileType, String fileName) throws IOException {
        log.info("picture path ===>{}", filePath);
        File file = new File(filePath);
        long fileLength = file.length();

        if (fileType.equals("txt")) {
            response.setContentType("text/plain;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("doc")) {
            response.setContentType("application/msword;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("xls")) {
            response.setContentType("application/ms-excel;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("pdf")) {
            response.setContentType("application/pdf;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png")) {
            response.setContentType("image/jpeg");
            response.setHeader("Content-Length", "" + fileLength);
        } else if (fileType.equals("amr")) {
            response.setContentType("audio/amr-wb");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else {
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        }
        InputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // response.setHeader("Content-Length", "" + fileLength);
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }
}
